package com.lcz.authority.common.service.file.impl;

import com.lcz.authority.common.config.ConfigExpander;
import com.lcz.authority.common.exception.ServiceException;
import com.lcz.authority.common.exception.constants.ErrorCodeConstants;
import com.lcz.authority.common.exception.file.InvalidExtensionException;
import com.lcz.authority.common.service.file.FileOperatorApi;
import com.lcz.authority.common.utils.file.FileUploadUtils;
import com.lcz.authority.common.utils.file.MimeTypeUtils;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author lcz
 * @desc 本地文件
 * @mail lcz_0130@163.com
 * @date 2024/05/07
 */

@Service("LocalFile")
public class LocalFile implements FileOperatorApi {

    /**
     * 默认上传的地址
     */
    @Getter
    @Setter
    private static String defaultBaseDir = ConfigExpander.getFileProfile();

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     */
    @Override
    public String upload(MultipartFile file) {
        return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
    }

    @Override
    public String upload(String baseDir, MultipartFile file) {
        return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
    }


    /**
     * 文件上传
     *
     * @param bucketName       相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     */
    @Override
    public String upload(String bucketName, MultipartFile file, String[] allowedExtension) {
        int fileNameLength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            String message = ErrorCodeConstants.FILE_NAME_LENGTH_LIMIT_EXCEED.getMessage();
            message = String.format(message, FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
            throw new ServiceException(message, ErrorCodeConstants.FILE_NAME_LENGTH_LIMIT_EXCEED.getCode());
        }

        try {
            FileUploadUtils.assertAllowed(file, allowedExtension);
        } catch (InvalidExtensionException e) {
            throw new RuntimeException(e);
        }

        String fileName = FileUploadUtils.extractFilename(file);

        String absPath;
        try {
            absPath = FileUploadUtils.getAbsoluteFile(bucketName, fileName).getAbsolutePath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            file.transferTo(Paths.get(absPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            return FileUploadUtils.getPathFileName(bucketName, fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
